package com.demo.systemmonitor;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;
import java.util.List;
import android.util.Log;
import android.support.v4.content.ContextCompat;
import com.demo.systemmonitor.R;

public class LineChart extends View {
	private static final String TAG = "LineChart";
	
	// 数据系列
	private List<Float> cpuUsageData = new ArrayList<>();
	private List<Float> cpuTempData = new ArrayList<>();
	private List<Float> cpuFreqData = new ArrayList<>();
	private List<Float> memoryUsageData = new ArrayList<>();
	
	// 绘制参数
	private Paint cpuUsagePaint, cpuTempPaint, cpuFreqPaint, memoryPaint;
	private Paint gridPaint, textPaint, axisPaint;
	private int maxDataPoints = 100;
	private float leftAxisMax = 100f;   // 左轴最大值，默认百分比
	private float rightAxisMax = 100f;  // 右轴最大值，按需启用
	private boolean rightAxisEnabled = false;
	private String leftAxisUnit = "%"; // 左轴单位
	private String rightAxisUnit = ""; // 右轴单位
	
	// 历史数据模式
	private boolean isHistoryMode = false;
	private List<String> timeLabels = null;
	
	// 颜色定义
	private int cpuUsageColor;
	private int cpuTempColor;
	private int cpuFreqColor;
	private int memoryUsageColor;
	private int gridColor;
	private int textColor;
	private int axisColor;
	
	// 图例参数
	private float legendSpacing = 75f; // 增大间距，避免重叠
	private float legendLineLength = 12f;
	
	// 内边距用于坐标轴与文字
	private float paddingLeftPx = 60f;
	private float paddingRightPx = 80f;
	private float paddingTopPx = 10f;
	private float paddingBottomPx = 36f;
	
	public LineChart(Context context) {
		super(context);
		init();
	}
	
	public LineChart(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}
	
	public LineChart(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init();
	}
	
	private void init() {
		// 从资源文件获取颜色，添加错误处理
		try {
			cpuUsageColor = getResources().getColor(R.color.cpu_usage_color);
			cpuTempColor = getResources().getColor(R.color.cpu_temp_color);
			cpuFreqColor = getResources().getColor(R.color.cpu_freq_color);
			memoryUsageColor = getResources().getColor(R.color.memory_usage_color);
			gridColor = getResources().getColor(R.color.chart_grid_color);
			textColor = getResources().getColor(R.color.chart_text_color);
			axisColor = getResources().getColor(R.color.chart_axis_color);
		} catch (Exception e) {
			Log.w(TAG, "Failed to load colors from resources, using fallback colors", e);
			// Fallback到硬编码颜色
			cpuUsageColor = Color.parseColor("#00FFFF");
			cpuTempColor = Color.parseColor("#FF0000");
			cpuFreqColor = Color.parseColor("#FFFF00");
			memoryUsageColor = Color.parseColor("#800080");
			gridColor = Color.LTGRAY;
			textColor = Color.WHITE;
			axisColor = Color.WHITE;
		}
		
		// 初始化画笔（使用获取到的颜色）
		cpuUsagePaint = new Paint();
		cpuUsagePaint.setColor(cpuUsageColor);
		cpuUsagePaint.setStrokeWidth(3f);
		cpuUsagePaint.setStyle(Paint.Style.STROKE);
		cpuUsagePaint.setAntiAlias(true);
		
		cpuTempPaint = new Paint();
		cpuTempPaint.setColor(cpuTempColor);
		cpuTempPaint.setStrokeWidth(3f);
		cpuTempPaint.setStyle(Paint.Style.STROKE);
		cpuTempPaint.setAntiAlias(true);
		
		cpuFreqPaint = new Paint();
		cpuFreqPaint.setColor(cpuFreqColor);
		cpuFreqPaint.setStrokeWidth(3f);
		cpuFreqPaint.setStyle(Paint.Style.STROKE);
		cpuFreqPaint.setAntiAlias(true);
		
		memoryPaint = new Paint();
		memoryPaint.setColor(memoryUsageColor);
		memoryPaint.setStrokeWidth(3f);
		memoryPaint.setStyle(Paint.Style.STROKE);
		memoryPaint.setAntiAlias(true);
		
		gridPaint = new Paint();
		gridPaint.setColor(gridColor);
		gridPaint.setStrokeWidth(1f);
		gridPaint.setStyle(Paint.Style.STROKE);
		gridPaint.setAntiAlias(true);
		
		textPaint = new Paint();
		textPaint.setColor(textColor);
		textPaint.setTextSize(16f);
		textPaint.setAntiAlias(true);
		
		axisPaint = new Paint();
		axisPaint.setColor(axisColor);
		axisPaint.setStrokeWidth(2f);
		axisPaint.setStyle(Paint.Style.STROKE);
		axisPaint.setAntiAlias(true);
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		
		int width = getWidth();
		int height = getHeight();
		
		float chartLeft = paddingLeftPx;
		float chartRight = width - paddingRightPx;
		float chartTop = paddingTopPx;
		float chartBottom = height - paddingBottomPx;
		
		// 绘制网格和坐标轴
		drawGrid(canvas, chartLeft, chartTop, chartRight, chartBottom);
		drawAxes(canvas, chartLeft, chartTop, chartRight, chartBottom);
		
		// 绘制数据线
		drawDataLines(canvas, chartLeft, chartTop, chartRight, chartBottom);
		
		// 绘制图例
		drawLegend(canvas, width, height);
	}
	
	private void drawGrid(Canvas canvas, float left, float top, float right, float bottom) {
		// 水平网格线（按左轴刻度5等分）
		for (int i = 0; i <= 5; i++) {
			float y = bottom - (bottom - top) * i / 5f;
			canvas.drawLine(left, y, right, y, gridPaint);
		}
		
		// 垂直网格线（按时间刻度6等分，从左到右均匀分布）
		for (int i = 0; i <= 6; i++) {
			float x = left + (right - left) * i / 6f;  // 修复：从左到右均匀分布
			canvas.drawLine(x, top, x, bottom, gridPaint);
		}
	}
	
	private void drawAxes(Canvas canvas, float left, float top, float right, float bottom) {
		// 绘制坐标轴
		axisPaint.setColor(axisColor);
		axisPaint.setStrokeWidth(2f);
		
		// X轴
		canvas.drawLine(left, bottom, right, bottom, axisPaint);
		// 左Y轴
		canvas.drawLine(left, top, left, bottom, axisPaint);
		// 右Y轴（如果启用）
		if (rightAxisEnabled) {
			canvas.drawLine(right, top, right, bottom, axisPaint);
		}
		
		// 删除重复的网格绘制代码，因为 drawGrid() 已经处理了
		
		// 绘制左Y轴标签
		textPaint.setColor(textColor);
		textPaint.setTextSize(12f);
		
		for (int i = 0; i <= 5; i++) {
			float value = leftAxisMax * i / 5f;
			float y = bottom - (bottom - top) * i / 5f;
			String label = (i == 5 ? String.format("%.1f%s", value, leftAxisUnit) : String.format("%.1f", value));
			canvas.drawText(label, left - 48f, y + 8f, textPaint);
		}
		
		// 绘制右Y轴标签（如果启用）
		if (rightAxisEnabled) {
			for (int i = 0; i <= 5; i++) {
				float value = rightAxisMax * i / 5f;
				float y = bottom - (bottom - top) * i / 5f;
				String label = (i == 5 ? String.format("%.1f%s", value, rightAxisUnit) : String.format("%.1f", value));
				canvas.drawText(label, right + 8f, y + 8f, textPaint);
			}
		}
		
		// 绘制X轴标签
		if (isHistoryMode && timeLabels != null && !timeLabels.isEmpty()) {
			// 历史数据模式：显示动态时间点
			for (int i = 0; i < timeLabels.size(); i++) {
				String timeLabel = timeLabels.get(i);
				float x = left + (right - left) * i / (float) (timeLabels.size() - 1);
				
				float textWidth = textPaint.measureText(timeLabel);
				float textX = x - textWidth / 2;
				canvas.drawText(timeLabel, textX, bottom + 20f, textPaint);
			}
		} else {
			// 实时监控模式：显示60s前到now
			for (int i = 0; i <= 6; i++) {
				float timeValue = 60 - (i * 10);  // 60, 50, 40, 30, 20, 10, 0
				String timeLabel = (timeValue == 0) ? "now" : timeValue + "s前";
				float x = left + (right - left) * i / 6f;
				
				float textWidth = textPaint.measureText(timeLabel);
				float textX = x - textWidth / 2;
				canvas.drawText(timeLabel, textX, bottom + 20f, textPaint);
			}
		}
	}
	
	private void drawDataLines(Canvas canvas, float left, float top, float right, float bottom) {
		// CPU使用率（左轴）
		drawDataLine(canvas, cpuUsageData, cpuUsagePaint, left, top, right, bottom, leftAxisMax);
		// CPU温度（右轴可选，若未启用则用左轴）
		float tempMax = rightAxisEnabled ? rightAxisMax : leftAxisMax;
		drawDataLine(canvas, cpuTempData, cpuTempPaint, left, top, right, bottom, tempMax);
		// CPU频率（右轴或左轴，按配置者决定传入的轴最大值）
		float freqMax = rightAxisEnabled ? rightAxisMax : leftAxisMax;
		drawDataLine(canvas, cpuFreqData, cpuFreqPaint, left, top, right, bottom, freqMax);
		// 内存使用率（左轴）或按调用配置
		drawDataLine(canvas, memoryUsageData, memoryPaint, left, top, right, bottom, leftAxisMax);
	}
	

// 恢复原始的 drawDataLine 方法
private void drawDataLine(Canvas canvas, List<Float> data, Paint paint,
        float left, float top, float right, float bottom, float axisMax) {
    if (data == null || data.size() < 2) return;
    
    Path path = new Path();
    boolean first = true;
    int n = data.size();
    
    for (int i = 0; i < n; i++) {
        float x;
        if (isHistoryMode) {
            // 历史数据模式：从左到右按时间顺序分布
            x = left + (right - left) * i / (float) (n - 1);
        } else {
            // 实时监控模式：按时间比例分布，最新数据在now位置
            x = right - (right - left) * (n - 1 - i) / 59f;
        }
        
        float value = data.get(i) == null ? 0f : data.get(i);
        float ratio = axisMax <= 0f ? 0f : (value / axisMax);
        if (ratio < 0f) ratio = 0f;
        if (ratio > 1f) ratio = 1f;
        float y = bottom - (bottom - top) * ratio;
        
        if (first) {
            path.moveTo(x, y);
            first = false;
        } else {
            path.lineTo(x, y);
        }
    }
    
    canvas.drawPath(path, paint);
}

// 删除错误的方法
// private void drawDataLine(Canvas canvas, List<Float> data, int color, String label) { ... }
// private int getColorForLabel(String label) { ... }
	
	private void drawLegend(Canvas canvas, int width, int height) {
		float startX = 70f;
		float y = 20f;
		float x = startX;
		
		// 检查是否需要换行
		String[] labels = {"CPU利用率", "CPU温度", "CPU频率", "内存使用率"};
		Paint[] paints = {cpuUsagePaint, cpuTempPaint, cpuFreqPaint, memoryPaint};
		
		// 创建小字体的文本画笔
		Paint smallTextPaint = new Paint(textPaint);
		smallTextPaint.setTextSize(10f); // 减小字体大小
		
		for (int i = 0; i < labels.length; i++) {
			float textWidth = smallTextPaint.measureText(labels[i]);
			if (x + textWidth + legendSpacing > width - 20f) {
				y += 28f;
				x = startX;
			}
			x = drawLegendEntry(canvas, x, y, paints[i], labels[i], smallTextPaint);
		}
	}
	
	private float drawLegendEntry(Canvas canvas, float x, float y, Paint paint, String label, Paint textPaint) {
		canvas.drawLine(x, y, x + legendLineLength, y, paint);
		canvas.drawText(label, x + legendLineLength + 6f, y + 8f, textPaint);
		return x + legendLineLength + legendSpacing ;
	}
	
	// 配置API
	public void setLeftAxis(String unit, float max) {
		this.leftAxisUnit = unit == null ? "" : unit;
		this.leftAxisMax = max <= 0 ? 100f : max;
		invalidate();
	}
	
	public void setRightAxisEnabled(boolean enabled, String unit, float max) {
		this.rightAxisEnabled = enabled;
		this.rightAxisUnit = unit == null ? "" : unit;
		this.rightAxisMax = max <= 0 ? 100f : max;
		invalidate();
	}
	
	public void setTimeAxisForHistoryData(List<String> timeLabels) {
		this.timeLabels = timeLabels;
		this.isHistoryMode = true;
		invalidate();
	}
	
	// 数据写入API
	private void addDataPoint(List<Float> data, float value) {
		data.add(value);
		if (data.size() > maxDataPoints) {
			data.remove(0);
		}
		invalidate();
	}
	
	// 历史数据加载
	public void loadHistoricalData(List<Float> cpuUsage, List<Float> cpuTemp,
			List<Float> cpuFreq, List<Float> memory) {
		this.cpuUsageData = cpuUsage == null ? new ArrayList<>() : new ArrayList<>(cpuUsage);
		this.cpuTempData = cpuTemp == null ? new ArrayList<>() : new ArrayList<>(cpuTemp);
		this.cpuFreqData = cpuFreq == null ? new ArrayList<>() : new ArrayList<>(cpuFreq);
		this.memoryUsageData = memory == null ? new ArrayList<>() : new ArrayList<>(memory);
		
		// 如果没有设置历史模式，则使用实时监控模式
		if (!isHistoryMode) {
			this.timeLabels = null;
		}
		
		invalidate();
	}
}
